package com.henry.base.concurrency.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AioAcceptHandler implements CompletionHandler<AsynchronousSocketChannel,AsynchronousServerSocketChannel> {
    public void cancelled(AsynchronousServerSocketChannel attachment) {
        System.out.println("cancelled");
    }


    @Override
    public void completed(AsynchronousSocketChannel result, AsynchronousServerSocketChannel attachment) {
        try {

        System.out.println("AioAcceptHandler.completed called");
        attachment.accept(attachment,this);
        System.out.println("有客户端连接:"+result.getRemoteAddress().toString());
        startRead(result);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void failed(Throwable exc, AsynchronousServerSocketChannel attachment) {
exc.printStackTrace();
    }

    public void startRead(AsynchronousSocketChannel socketChannel) {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        socketChannel.read(buffer, buffer, new AioReadHandler(socketChannel));
        try {

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
